package com.tjetc.common;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.util.Random;

/**
 * 专门用来生成验证码的util
 * */
@Component
public class CodeUtil {
    @Autowired
    private CaptchaImgInfo captchaImgInfo;
    private final Random random = new Random();

    public String generateCaptcha() {
        StringBuilder captcha = new StringBuilder();
        BufferedImage image = new BufferedImage(captchaImgInfo.getWidth(), captchaImgInfo.getHeight(), BufferedImage.TYPE_INT_RGB);
        Graphics2D graphics = image.createGraphics();

        // 设置背景色
        graphics.setColor(Color.WHITE);
        graphics.fillRect(0, 0, captchaImgInfo.getWidth(), captchaImgInfo.getHeight());

        // 设置字体
        Font font = new Font("Arial", Font.BOLD, 18);
        graphics.setFont(font);

        // 生成随机字符并绘制到图像上
        for (int i = 0; i < 6; i++) {
            char randomChar = captchaImgInfo.getCharset().charAt(random.nextInt(captchaImgInfo.getCharset().length()));
            captcha.append(randomChar);
            int x = 10 + i * (captchaImgInfo.getWidth() / 6 - 10);
            int y = captchaImgInfo.getHeight() / 2 + random.nextInt(5);
            graphics.setColor(new Color(random.nextInt(256), random.nextInt(256), random.nextInt(256)));
            graphics.drawString(String.valueOf(randomChar), x, y);
        }

        graphics.dispose();

        return captcha.toString();
    }

    public byte[] generateCaptchaImage(String captcha) throws Exception {
        BufferedImage image = new BufferedImage(captchaImgInfo.getWidth(), captchaImgInfo.getHeight(), BufferedImage.TYPE_INT_RGB);
        Graphics2D graphics = image.createGraphics();

        // 设置背景色
        graphics.setColor(Color.WHITE);
        graphics.fillRect(0, 0, captchaImgInfo.getWidth(), captchaImgInfo.getHeight());

        // 设置字体
        Font font = new Font("Arial", Font.BOLD, 18);
        graphics.setFont(font);

        // 绘制验证码文本
        int x = 10;
        int y = captchaImgInfo.getHeight() / 2 + random.nextInt(5);
        graphics.setColor(Color.BLACK);
        graphics.drawString(captcha, x, y);

        graphics.dispose();

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ImageIO.write(image, "png", baos);

        return baos.toByteArray();
    }
}
